#!/usr/bin/perl
#
# patch - patch any field in any record
# note - because of file specified dynamic loading, some changes
# will cause strange/large things to happen...
#
use POSIX;
# note - tool needs Counter init routines to get right DB.
# this makes it somewhat ungeneral....
#use FileTable;
use Counter;

$operation = "change";

while ($ARGV[0] =~ /^-/) {
    $opt = shift;
    if ($opt eq "-d") {
	$operation = "clear";
    } elsif ($opt eq "-c") {
	$operation = "create";
    } elsif ($opt eq "-p") {
	$operation = "patch";
    } else {
	die "Usage: $0 [-d|-c] filename recno [field value]\n";
    }
}


$filename = shift;
$recno = shift;
$field = shift;
$value = shift;

if (! -f "$filename.conf") {
    $filename = $ENV{COUNTER_ROOT} . "/db/" . $filename;
}
    
$file = FileTable::open($filename, O_RDWR);
die "Unable to open $file\n" if !$file;
if ($operation eq "change" || $operation eq "patch") {
    $rec = $file->get($recno) || die "$recno: No such record\n";
    if (length($rec->{$field}) > 0) {
	print "$recno: Changing $field from $rec->{$field} to $value\n";
    } else {
	print "$recno: Adding $field: $value\n";
    } 
    if (length($value) == 0) {
	print "$recno: Clearing $field\n";
	delete $rec->{$field};
    } else {
	$rec->{$field} = $value;
    }
    if ($operation eq "patch") {
	print "$recno: using patch()\n";
	$rec->patch;
    } else {
	$rec->store;
    }
} elsif ($operation eq "clear") {
    $rec = $file->get($recno) || die "$recno: No such record\n";
    print "Deleting record\n";
    $rec->delete;
} elsif ($operation eq "create") {
    die "Already exists" if $file->get($recno);
    $rec = $file->get($recno, O_CREAT);
    print "New $recno: Adding $field: $value\n";
    $rec->{$field} = $value;
    $rec->store;
} else {
    die "Internal error: Unknown operation: $operation\n";
}









